
#include <BViewer>
#include <BPainter>
#include <BRender>
#include <BMaterial>
#include <BMouseEvent>
#include <BReadWrite>
#include <BScene>

#include "TerrainCreater.h"

TerrainCreater::TerrainCreater()
{
	this->setName("Create Ground");
	_radius = 0.0f;
	_count = 0;
}
TerrainCreater::~TerrainCreater()
{

}

void TerrainCreater::slotAssetChanged(BObject* object, const BValue& value)
{
	disconnect(object);
}

void TerrainCreater::paint(BPainter& painter)
{
	if (_count == 1)
	{
		BVector offset = _points[1] - _points[0];
		BReal length = offset.x();
		BReal width = offset.y();
		BString text;
		text << "length : " << length;
		text << "width : " << width;
		painter.setColor(1, 1, 1);
		painter.drawText(0, 0, text);
	}
}
void TerrainCreater::render(BRender& render)
{
	render.setColor(0, 1, 0);
	render.drawVertex(_points[_count]);
}

void TerrainCreater::updateEvent(const BEvent& event)
{

}

void TerrainCreater::mousePressEvent(const BMouseEvent& mouseEvent)
{
	Button button = mouseEvent.button();
	BPoint pos = mouseEvent.pos();
	if (button == Button_Left)
	{
		if (_count == 0)
		{
			BString name("Terrain");
			//findValidName(this->scene(), name);
			_terrain = new BTerrain();
			_terrain->setName(name);
			_terrain->setPosition(_points[0]);
			this->scene()->insert(_terrain);
			_count++;
			mouseEvent.accept();
		}
		if (_count == 1)
		{
			connect(_terrain, Signal_AssetChanged, &TerrainCreater::slotAssetChanged);
			mouseEvent.accept();
		}
	}
}
void TerrainCreater::mouseReleaseEvent(const BMouseEvent& mouseEvent)
{

}
void TerrainCreater::mouseMoveEvent(const BMouseEvent& mouseEvent)
{
	BPoint pos = mouseEvent.pos();
	BLine line = this->viewer()->line(pos);
	BPlane plane(BVector(0, 0, 1), _center);
	BVector point;
	if (line.intersect(plane, point))
	{
		_points[_count] = point;
		this->fresh();
	}
	if (_count == 1)
	{
		BSpace space = _points[0];
		space.expand(_points[1]);
		BReal width = space.width();
		BReal height = space.height();
		_terrain->setPosition(space.min());
		_terrain->setWidth(width);
		_terrain->setHeight(height);
	}
}
